<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /* 
        可以用递归也可以用迭代
        
        */
      /*       var countNodes = function (root) {
        let count = 0
        function preOrder(root) {
          if (!root) return null
          count++
          preOrder(root.left)
          preOrder(root.right)
        }
        preOrder(root)
        return count
      } */

      //迭代 即层序遍历
      let tree = {
        val: 1,
        left: {
          val: 2,
          left: {
            val: 4,
          },
          right: {
            val: 5,
          },
        },
        right: {
          val: 3,
          right: {
            val: 7,
          },
        },
      }
      var countNodes = function (root) {
        let sum = 0
        function levelOrder(root) {
          if (!root) return []
          let queue = [root]
          let res = []
          while (queue.length) {
            res.push([])
            let len = queue.length
            for (let i = 0; i < len; i++) {
              let node = queue.shift()
              if (!node) {
                res[res.length - 1].push(null)
              } else {
                res[res.length - 1].push(node.val)
                queue.push(node.left)
                queue.push(node.right)
              }
            }
          }
          return res
        }
        console.log(levelOrder(root))
      }
      countNodes(tree)
    </script>
  </body>
</html>
